import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { FormBuilder, Validators, FormControl } from "@angular/forms";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { TurbStatusExprService } from "../../../../service/turbstatus_expr.service";
import { TurbStatusService } from "../../../../service/turbstatus.service";
import { TurbStatusExpr, TurbStatusExprData, TagMark } from "../../../../entity/turbstatus-expr.model";


@Component({
  selector: 'app-staus-exper-edit',
  templateUrl: './staus-exper-edit.component.html',
  styleUrls: ['./staus-exper-edit.component.css']
})
export class StausExperEditComponent extends BladeContainerBase<TurbStatusExpr> {


  canSave: boolean;
  /**
   * 测点标识
   * 
   * @type {TagMark[]}
   * @memberof StausExperEditComponent
   */
  tagMark: TagMark[] = []


  /**
   * 验证结果
   * 
   * @type {boolean}
   * @memberof StausExperEditComponent
   */
  result: any;


  constructor(private fb: FormBuilder,
    private turbStatusExprService: TurbStatusExprService) {
    super(fb);


  }

  ngOnInit(): void {
    this.commands = [
      new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
      new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
    ]
    super.ngOnInit();
    this.tagMark = this.parentEntity;
    this.tagMark.forEach(item => {
      if (!item.value) {
        item.value = 1;
      }
    })

  }


  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    // return this.hasChange() && !this.hasError();
    return this.canSave === true || this.hasChange() && !this.hasError();
  }
  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    return this.hasChange();
  }

  saveChange(): any | Promise<any> | Observable<any> {
    //校验
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      //this.currentEntity.expr = formValue.expr;
      let str = formValue.expr;
      let reg = new RegExp("@[A-Z]#", 'g');
      // let curstr = str.match(reg).join().split(',');
      let curstr = str.match(reg) != null ? str.match(reg).join().split(',') : [];

      for (let i = 0; i < this.tagMark.length; i++) {
        let curValue = this.tagMark[i].value;
        let curTagStateMark = "@" + this.tagMark[i].tagStateMark + "#";
        for (let j = 0; j < curstr.length; j++) {
          if (curTagStateMark == curstr[j]) {
            str = str.replace(new RegExp("@[A-Z]#", 'g'), function (a) {
              a = curValue.toString();
              return a;
            })
          }
        }
      }

      this.turbStatusExprService.exprCheck(str)
        .then(res => {
          //this.result = res;


          //(this.parentBlade.bladeContainerInstance).refresh(this.currentEntity);
          //保存
          if (res.code == 200) {
            this.result = res.data.expr;
            this.canSave = true;
            this.currentEntity.expr = formValue.expr;
            if (this.canSaveChange(this.currentBlade)) {
              this.bladeData.isLoading = true;
              let formValue = this.formGroup.value;
              this.currentEntity.expr = formValue.expr;
              this.currentEntity.expr = this.currentEntity.expr;
              return this.turbStatusExprService.update(this.currentEntity)
                .then(res => {
                  if (res) {
                    (this.parentBlade.bladeContainerInstance).refresh(res);
                    this.bladeService.closeBlade(this.currentBlade);
                    return true;
                  }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
            }
          } else if (res.code == -1) {
            this.result = res.message;
            this.canSave = false;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }



  }

  /**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
  createForm() {
    this.formGroup = this.fromBuider.group({
      "result": [this.currentEntity.result, []],
      "statusName": [this.currentEntity.statusName, [
        Validators.required,
        Validators.maxLength(20),
      ]],
      "expr": [this.currentEntity.expr, [
        Validators.required,
        Validators.maxLength(200),
      ]],
    });
  }

  /**
  * 设置表单错误对象
  * 
  * 
  * @memberof BladeContainerBase
  */
  setFormError(): void {
    this.formErrors = {
      'statusName': '',
      'expr': '',
    };
  }

  /**
 * 设置表单验证信息
 * 
 * 
 * @memberof BladeContainerBase
 */
  setValidationMessages(): void {
    this.validationMessages = {
      'statusName': {
        'required': '不能为空。',
        'maxlength': '状态名不能多于20个字符长度。',
        'exist': '状态名已存在',
      },
      'expr': {
        'required': '不能为空。',
        'maxlength': '表达式不能多于20个字符长度。'
      }

    };
  }

  /**
     * 校验
     * 
     * 
     * @memberof DicKeyEditComponent
     */
  onCheck(): any {
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      this.currentEntity.expr = formValue.expr;
      let str = this.currentEntity.expr;
      let reg = new RegExp("@[A-Z]#", 'g');
      // let curstr = str.match(reg).join().split(',');
      let curstr = str.match(reg) != null ? str.match(reg).join().split(',') : [];

      for (let i = 0; i < this.tagMark.length; i++) {
        let curValue = this.tagMark[i].value;
        let curTagStateMark = "@" + this.tagMark[i].tagStateMark + "#";
        for (let j = 0; j < curstr.length; j++) {
          if (curTagStateMark == curstr[j]) {
            str = str.replace(new RegExp("@[A-Z]#", 'g'), function (a) {
              a = curValue.toString();
              return a;
            })
          }
        }
      }

      this.turbStatusExprService.exprCheck(str)
        .then(res => {
          if (res.code == 200) {
            this.result = res.data.expr;
            this.canSave = true;
          } else if (res.code == -1) {
            this.result = res.message;
            this.canSave = false;
          }
          ///this.result = res;          
          (this.parentBlade.bladeContainerInstance).refresh(this.currentEntity);
        })


        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }





}
export interface Result {
  code: number;
  messages: string;
}


// WEBPACK FOOTER //
// ./src/app/module/basic/staus-exper/staus-exper-edit/staus-exper-edit.component.ts